package Dao.DaoImpl;

import Dao.BreakRuleDao;
import Utils.JDBCUtils;
import domain.BreakRule;
import domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class BreakRuleDaoImpl implements BreakRuleDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public void addBreakRuleDao(BreakRule rule) {
        String sql = "insert into breakrule values(null,?,?,?,?)";
        template.update(sql,rule.getStunum(),rule.getName(),rule.getDisReason(),rule.getWriteTime());
    }

    @Override
    public List<BreakRule> fuzzySelectBreakRule(HashMap<String,String> map) {
        String sql = "select * from breakrule where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        Set<String> set = map.keySet();
        List<Object> params = new ArrayList<Object>();
        for (String key : set) {
            String value = map.get(key);

            //判断value是否有值
            if(value!=null && !"".equals(value)){
                //有值就拼接
                sb.append(" and "+key+" like ?");
                params.add("%"+value+"%");//上面 ?的值
            }
        }

        sql = sb.toString();

        return template.query(sql,new BeanPropertyRowMapper<>(BreakRule.class),params.toArray());
    }

    @Override
    public List<BreakRule> breakRuleList() {
        String sql ="select * from breakrule";
        return template.query(sql,new BeanPropertyRowMapper<>(BreakRule.class));
    }

    @Override
    public BreakRule selectBreakRuleById(int id) {
        String sql ="select * from breakrule where id = ?";
        return template.queryForObject(sql,new BeanPropertyRowMapper<>(BreakRule.class),id);
    }

    @Override
    public void DelBreakRule(int id) {
        String sql ="delete from breakrule where id=?";
        template.update(sql,id);
    }

    @Override
    public void UpdateBreakRule(BreakRule Rule, int id) {
        String sql = "update breakrule set stunum=?,name=?,disReason=? where id = ?";
        template.update(sql,Rule.getStunum(),Rule.getName(),Rule.getDisReason(),id);
    }
}
